package com.standardoperationapp.operationplan;


import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ArrayAdapter;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.bumptech.glide.Glide;
import com.cl.picture_selector.ImagePicker;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.standardoperationapp.R;
import com.standardoperationapp.activity.BluetoothSetActivity;
import com.standardoperationapp.adapter.CardPointStepAdapter;
import com.standardoperationapp.bean.CardPointBean;
import com.standardoperationapp.bean.CardPointStepBean;
import com.standardoperationapp.databinding.ActivityPointOperateBinding;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.net.MaterialApi;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;
import com.standardoperationapp.net.OperationApi;
import com.standardoperationapp.utils.FileUtils;
import com.standardoperationapp.utils.GlideLoader;
import com.standardoperationapp.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


/**
 * 卡控点操作
 */
public class PointDetailActivity extends AppCompatActivity {

    private ActivityPointOperateBinding binding;
    private CardPointStepBean stepBean;

    private int planId;
    private int implementId;
    private int workPointId;

    private ActivityResultLauncher<PickVisualMediaRequest> launcher;
    private int REQUEST_CODE=100;
    private int id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_point_operate);

        String title = getIntent().getStringExtra("title");
        stepBean = (CardPointStepBean) getIntent().getSerializableExtra("bean");
        planId = getIntent().getIntExtra("planId", 0);
        implementId = getIntent().getIntExtra("implementId", 0);
        workPointId = getIntent().getIntExtra("workPointId", 0);
        binding.tvTitle.setText(title);

        initView();


        launcher = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                Log.d("PhotoPicker", "Selected URI: " + uri);
                String path = FileUtils.getRealPathFromUri(this, uri);
                Log.d("PhotoPicker", "Selected path: " + path);
                uploadPhoto(path);
            } else {
                Log.d("PhotoPicker", "No media selected");
            }
        });
    }

    private void  initView(){

        binding.pointListView.setOnItemClickListener((adapterView, view, i, l) -> {
            id = stepBean.getData().get(i).getId();
            String type = stepBean.getData().get(i).getExcutableType();
            if (stepBean.getData().get(i).getOperateStatus().equals("1")) {
                ToastUtil.showToast("请勿重复操作");
                return;
            }
            switch (type) {
                case "execute_status":
                    //可执行状态确认
                    AlertDialog dialog = new AlertDialog.Builder(this)
                            .setTitle("可执行状态确认")
                            .setMessage("确认执行【"+stepBean.getData().get(i).getMethodName()+"】操作？")
                            .setPositiveButton("确定", (dialogInterface, i1) -> {
                                dialogInterface.dismiss();
                                submitExecuteStatus(id);
                            })
                            .setNegativeButton("取消", (dialogInterface, i12) -> dialogInterface.dismiss())
                            .show();
                    break;
                case "result_text":
                    //10 作业结果录入
                    break;
                case "close_protection":
                    //8 结束联控防护
                    Intent intent = new Intent(this, ProtectionActivity.class);
                    intent.putExtra("planId", planId);
                    intent.putExtra("workPointId", workPointId);
                    intent.putExtra("id", id);
                    intent.putExtra("type", 0);
                    startActivity(intent);
                    break;
                case "enable_protection":
                    //7开启联控防护
                    intent = new Intent(this, ProtectionActivity.class);
                    intent.putExtra("planId", planId);
                    intent.putExtra("workPointId", workPointId);
                    intent.putExtra("id", id);
                    intent.putExtra("type", 1);
                    startActivity(intent);
                    break;
                case "check_num":
                    //工器具数据核验
                    intent = new Intent(this, CheckNumActivity.class);
                    intent.putExtra("planId", planId);
                    intent.putExtra("workPointId", workPointId);
                    intent.putExtra("id", id);
                    startActivity(intent);
                    break;
                case "in_net":
                case "out_net":
                    // 入网操作  申请出网
                    startActivity(new Intent(PointDetailActivity.this, BluetoothSetActivity.class));
                    break;
                case "file":
                    // 2 拍照
                    takePhoto();
                    break;
                case "face":
                    // 4 人脸识别
                    intent = new Intent(this, ProtectionActivity.class);
                    intent.putExtra("planId", planId);
                    intent.putExtra("workPointId", workPointId);
                    intent.putExtra("id", id);
                    intent.putExtra("type", 2);
                    startActivity(intent);
                    break;
                case "alcohol":
                    // 3 酒精检测
                    intent = new Intent(this, ProtectionActivity.class);
                    intent.putExtra("planId", planId);
                    intent.putExtra("workPointId", workPointId);
                    intent.putExtra("id", id);
                    intent.putExtra("type", 3);
                    startActivity(intent);
                    break;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPointOperation();
    }

    private void getPointOperation() {
        OperationApi.selectPointOperateByPointId(workPointId, planId, implementId, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                stepBean = GsonUtils.fromJson(result, CardPointStepBean.class);
                CardPointStepAdapter adapter = new CardPointStepAdapter(PointDetailActivity.this, stepBean.getData());//装配适配器
                binding.pointListView.setAdapter(adapter);
            }

            @Override
            public void onFault(String errorMsg) {
                ToastUtil.showToast(errorMsg);
            }
        }));

    }

    /**
     * 执行状态确认
     */
    private void submitExecuteStatus(int pointExecutableMethodId) {
        Map<String, Object> map = new HashMap<>();
        map.put("planId", planId);
        map.put("workPointId", workPointId);
        map.put("pointExecutableMethodId", pointExecutableMethodId);
        map.put("executableStatus", 1);
        OperationApi.recordPliAndDetail(map, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                getPointOperation();
            }

            @Override
            public void onFault(String errorMsg) {
                ToastUtil.showToast(errorMsg);
            }
        }));
    }

    // 选择照片
    private void takePhoto() {
        if (Build.VERSION.SDK_INT >= 33) {
            launcher.launch(new PickVisualMediaRequest.Builder()
                    .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                    .build());
        } else {
            //单选
            ImagePicker.getInstance()
                    .setTitle("选择照片")//设置标题
                    .showCamera(true)//设置是否显示拍照按钮
                    .showImage(true)//设置是否展示图片
                    .showVideo(false)//设置是否展示视频
                    .showLoading(true, "")   //是否显示首次加载框--加载框标题
                    .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
                    .setSingleType(true)//设置图片视频不能同时选择
                    .setImageLoader(new GlideLoader())//设置自定义图片加载器
                    .start(this, REQUEST_CODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            //获取选择器返回的数据
            List<String> images = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            uploadPhoto(images.get(0));

        }
    }

    private void uploadPhoto(String path){
        File mFile = new File(path);
        // 上传文件参数
        RequestBody body = RequestBody.create(MediaType.parse("image/jpg"), mFile);
        MultipartBody.Part file = MultipartBody.Part.createFormData("file", mFile.getName(), body);

        MaterialApi.uploadFile(file, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    JSONObject data = jsonObject.getJSONObject("data");

                    Map<String, Object> map = new HashMap();
                    map.put("planId", planId);
                    map.put("tapeUrl", data.getString("url"));
                    map.put("tapeType", "picture");
                    map.put("implementId", implementId);
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(map);
                    OperationApi.updateImage(list, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                        @Override
                        public void onSuccess(Object result) {
                            ToastUtil.showToast("照片提交成功");
                            submitExecuteStatus(id);
                        }

                        @Override
                        public void onFault(String errorMsg) {
                            ToastUtil.showToast("照片提交失败："+errorMsg);
                        }
                    }));


                } catch (JSONException e) {
                    ToastUtil.showToast("照片解析失败："+ e.toString());
                }

            }

            @Override
            public void onFault(String errorMsg) {
                ToastUtil.showToast("照片上传失败：" + errorMsg);
            }
        }));
    }
}